package at.fhooe.mcm12.java.sensors;

import java.rmi.RemoteException;
import java.util.Date;
import java.util.Random;
import java.util.Vector;

import at.fhooe.mcm12.java.enums.OutputFormat;
import at.fhooe.mcm12.java.interfaces.ISensorListener;
import at.fhooe.mcm12.java.sensors.data.LightIntensity;
import at.fhooe.mcm12.java.sensors.data.SensorValue;
import at.fhooe.mcm12.java.serializer.LightIntensitySerializer;

public class LightSensor extends PushSensor{

	private Random m_intensityGenerator;
	
	public LightSensor() throws RemoteException
	{
		super();
		Date dt = new Date();
		
		m_dataType = new LightIntensity(0,"lux",dt.getTime());
		m_intensityGenerator = new Random();
		m_sensorListener = new Vector<ISensorListener>();
		m_serializer = new LightIntensitySerializer();
		m_isSubscribable = true;
		
		m_description = "Provides information regarding the current light situation in lux.";
		Thread t = new Thread(this);
		t.start();
	}
	
	public String getUnit()
	{
		return m_dataType.getUnit();
	}
	
	public void setUnit(String _unit)
	{
		m_dataType.setUnit(_unit);
	}
	
	private void updateIntensity()
	{
		m_dataType.setTimestamp(new Date().getTime());
		((LightIntensity)m_dataType).setIntensity(10000 + (m_intensityGenerator.nextGaussian() * 50));
	}
	
	@Override
	public void push() {
		
		updateIntensity();
		
		for(ISensorListener listener : m_sensorListener)
		{
			try {
				listener.onSensorValueReceived(this.getName(), m_dataType);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
		
		serialize(OutputFormat.XML, m_dataType);
		serialize(OutputFormat.CSV, m_dataType);
		serialize(OutputFormat.Text, m_dataType);
	}

	@Override
	public void serialize(OutputFormat _format, SensorValue _value) {
		m_serializer.serialize(_format, _value);
	}
}
